/*
 * Copyright 2012 JooKar BV (info@jookar.nl)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package nl.jookar.android.utils.misc;


import android.content.ContentResolver;
import android.content.Context;
import android.provider.Settings;
import android.util.Log;

/**
 * @author Joost A. Bloemsma
 *
 */
public class SystemUtils {
	private static final String DEBUG_TAG = SystemUtils.class.getName();
	
	/**
	 * Utility method to create an instance of a class.<br/>
	 * The result is casted to the correct type, and exceptions can be ignored. 
	 * @param cls
	 * @return Typecasted instance of passed class
	 */
	public static <T> T createInstance(Class<T> cls) {
		try {
			return cls.newInstance();
		} catch (Exception e) {
			Log.d(DEBUG_TAG, "Error instantiating class " + cls.getName(), e);
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * Convenience method for {@link android.provider.Settings.System#getInt(android.content.ContentResolver, String, int)}.  
	 * @param ctx Used to get the {@link ContentResolver}
	 * @param name Name of the parameter
	 * @return the setting, or null if not found
	 */
	public static int getSettingInt(Context ctx, String name) {
		return getSettingInt(ctx, name, (Integer) null);
	}
	
	/**
	 * Convenience method for {@link android.provider.Settings.System#getInt(android.content.ContentResolver, String, int)}.
	 * @param ctx Used to get the {@link ContentResolver}
	 * @param name Name of the parameter
	 * @param def The default value if the setting is not found
	 * @return the setting, or the default if not found
	 */
	public static int getSettingInt(Context ctx, String name, int def) {
		return Settings.System.getInt(ctx.getContentResolver(), name, def);
	}
	
	/**
	 * Convenience method for {@link android.provider.Settings.System#putInt(ContentResolver, String, int)}.<br/>
	 * If the setting could not be set for some reason (eg putInt returns false) a {@link RuntimeException} is thrown. 
	 * @param ctx Used to get the {@link ContentResolver}
	 * @param name Name of the parameter
	 * @param value the integer to set
	 */
	public static void setSetting(Context ctx , String name, int value) {
		if (!Settings.System.putInt(ctx.getContentResolver(), name, value)) {
			throw new RuntimeException("Could not write value to systemsetting " + name);
		}
	}
}
